package org.jfinancegraph.gui;

import java.awt.Container;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.jfinancegraph.gui.components.table.ListTableModel;
import org.jfinanceobserver.persistence.ConnFactory;
import org.jfinanceobserver.persistence.jpa.controller.QuotesActiveJpaController;
import org.jfinanceobserver.persistence.jpa.controller.QuotesDataJpaController;
import org.jfinanceobserver.persistence.jpa.entities.QuotesActive;
import org.jfinanceobserver.utillities.QuotesActives;
import org.jfinanceobserver.utillities.Util;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.data.time.TimeSeriesCollection;

/**
 * This is a main class for the GUI
 *
 * $Author: r78v10a07@gmail.com $ $LastChangedDate: 2013-02-15 15:01:33 +0000 (Fri, 15 Feb 2013) $ $LastChangedRevision: 36 $
 *
 * @since Feb 14, 2013
 */
public class GUIPlot extends javax.swing.JFrame {

    private TimePlot plot;

    /**
     * Creates new form GUIPlot
     */
    public GUIPlot() {
        plot = new TimePlot();
        openDate = Util.getInstance().openDate();
        closeDate = Util.getInstance().closeDate();
        initComponents();
        jPanel1.setVisible(false);
    }

    private void loadQuotes() {
        ListTableModel model = (ListTableModel) jTQuotes.getModel();
        for (QuotesActive a : QuotesActives.getInstance().getActives()) {
            List quote = new ArrayList();
            quote.add(a.getSymbol());
            model.addRow(quote);
        }
        model.fireTableDataChanged();
    }

    private void createPlot() {
        ListTableModel model = (ListTableModel) jTQuotes.getModel();
        int selected[] = jTQuotes.getSelectedRows();

        plot.getSymbol().clear();
        if (selected != null) {
            for (int i = 0; i < selected.length; i++) {
                plot.getSymbol().add((String) model.getValueAt(selected[i], 0));
            }
        }

        if (plot.getSymbol().isEmpty()) {
            plot.getSymbol().add((String) model.getValueAt(0, 0));
        }

        Container contentPane = getContentPane();
        for (int i = 0; i < contentPane.getComponentCount(); i++) {
            if (contentPane.getComponent(i) instanceof ChartPanel) {
                ((ChartPanel) contentPane.getComponent(i)).setChart(plot.chartPlot((String) jCValue.getSelectedItem(), jDateFrom.getDate(), jDateTo.getDate()));
                break;
            }
        }
        validate();
        setVisible(true);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new ChartPanel(ChartFactory.createTimeSeriesChart("","","", new TimeSeriesCollection(),true,true,false));
        jCValue = new javax.swing.JComboBox();
        jDateFrom = new com.toedter.calendar.JDateChooser();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jDateTo = new com.toedter.calendar.JDateChooser();
        jBReload = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTQuotes = new javax.swing.JTable();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMLogIn = new javax.swing.JMenuItem();
        jMLogOut = new javax.swing.JMenuItem();
        jMExit = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("JFinanceObserver");

        jPanel1.setName("ChartPanel"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 682, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        jCValue.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Bit", "Ask", "Volume" }));
        jCValue.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCValueActionPerformed(evt);
            }
        });

        jDateFrom.setDate(openDate);
        jDateFrom.setDateFormatString("yyyy/MM/dd HH:mm:ss");

        jLabel2.setText("From:");

        jLabel3.setText("To:");

        jDateTo.setDate(closeDate);
        jDateTo.setDateFormatString("yyyy/MM/dd HH:mm:ss");

        jBReload.setText("Reload");
        jBReload.setActionCommand("");
        jBReload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBReloadActionPerformed(evt);
            }
        });

        jTQuotes.setModel(new ListTableModel(new String[] {"Active"}, new ArrayList<List<Object>>(),
            new Class[] {java.lang.Object.class}, new boolean[] {false}));
    jTQuotes.setColumnSelectionAllowed(true);
    jTQuotes.setGridColor(new java.awt.Color(230, 230, 230));
    jTQuotes.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jTQuotesMouseClicked(evt);
        }
    });
    jScrollPane1.setViewportView(jTQuotes);
    jTQuotes.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    jMenu1.setText("File");

    jMLogIn.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.CTRL_MASK));
    jMLogIn.setText("LogIn");
    jMLogIn.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jMLogInActionPerformed(evt);
        }
    });
    jMenu1.add(jMLogIn);

    jMLogOut.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
    jMLogOut.setText("LogOut");
    jMLogOut.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jMLogOutActionPerformed(evt);
        }
    });
    jMenu1.add(jMLogOut);

    jMExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
    jMExit.setText("jMExit");
    jMExit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jMExitActionPerformed(evt);
        }
    });
    jMenu1.add(jMExit);

    jMenuBar1.add(jMenu1);

    jMenu2.setText("Edit");
    jMenuBar1.add(jMenu2);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jCValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jDateFrom, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel3)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jDateTo, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jBReload))
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jCValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jDateFrom, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jBReload)
                            .addComponent(jDateTo, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 590, Short.MAX_VALUE))
            .addContainerGap())
    );

    pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jCValueActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCValueActionPerformed
        createPlot();
    }//GEN-LAST:event_jCValueActionPerformed

    private void jBReloadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBReloadActionPerformed
        createPlot();
    }//GEN-LAST:event_jBReloadActionPerformed

    private void jMLogInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMLogInActionPerformed
        OpenDB login = new OpenDB(this, true);
        login.toFront();
        login.setLocationRelativeTo(this);
        login.setVisible(true);
        if (!login.isCanceled()) {
            loadQuotes();
            plot.setaController(new QuotesActiveJpaController(ConnFactory.getInstance().getFactory()));
            plot.setdController(new QuotesDataJpaController(ConnFactory.getInstance().getFactory()));
            jPanel1.setVisible(true);
            createPlot();
        }
    }//GEN-LAST:event_jMLogInActionPerformed

    private void jMLogOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMLogOutActionPerformed
        ConnFactory.getInstance().close();
        ListTableModel model = (ListTableModel) jTQuotes.getModel();
        model.setContents(new ArrayList<List<Object>>());
        jPanel1.setVisible(false);
    }//GEN-LAST:event_jMLogOutActionPerformed

    private void jMExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMExitActionPerformed
        jMLogOutActionPerformed(evt);
        System.exit(0);
    }//GEN-LAST:event_jMExitActionPerformed

    private void jTQuotesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTQuotesMouseClicked
        createPlot();
    }//GEN-LAST:event_jTQuotesMouseClicked

    public void iter() {
        while (true) {
            if (ConnFactory.getInstance().getFactory() != null && ConnFactory.getInstance().getFactory().isOpen()) {
                createPlot();
            }
            try {
                Thread.sleep(Util.getInstance().openInterval);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUIPlot.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>


        GUIPlot plot = new GUIPlot();
        plot.setVisible(true);
        plot.iter();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBReload;
    private javax.swing.JComboBox jCValue;
    private com.toedter.calendar.JDateChooser jDateFrom;
    private com.toedter.calendar.JDateChooser jDateTo;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenuItem jMExit;
    private javax.swing.JMenuItem jMLogIn;
    private javax.swing.JMenuItem jMLogOut;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTQuotes;
    // End of variables declaration//GEN-END:variables
    private Date openDate;
    private Date closeDate;
}
